package org.example.secondkill.controller;

import org.example.secondkill.domain.Goods;
import org.example.secondkill.domain.Order;
import org.example.secondkill.rabbitmq.MQSender;
import org.example.secondkill.rabbitmq.OrderMessage;
import org.example.secondkill.redis.GoodsKey;
import org.example.secondkill.redis.OrderKey;
import org.example.secondkill.redis.RedisService;
import org.example.secondkill.redis.SecondKillKey;
import org.example.secondkill.response.BaseResponse;
import org.example.secondkill.response.ResultCode;
import org.example.secondkill.service.IGoodsService;
import org.example.secondkill.service.IKillService;
import org.example.secondkill.service.IOrderService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/kill")
@EnableScheduling
public class KillController implements InitializingBean {
    /**
     * 内存标记:
     * 存储商品是否已经超过了秒杀时间，即结束秒杀了，true-结束秒杀，false-仍旧可以秒杀
     * 相当于对 redis 的缓存, 如果为 true 就不需要访问 redis
     */
    private final Map<Long, Boolean> killEndFlag = new HashMap<>();
    @Autowired
    MQSender sender;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IKillService killService;

    /**
     * 系统初始化时调用
     * 将所有商品库存数量缓存到 redis
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<Goods> goodsList = goodsService.getAllGoods();
        if (goodsList == null) {
            return;
        }

        for (Goods goods : goodsList) {
            // 将所有商品库存数量缓存到 redis
            redisService.set(
                    GoodsKey.getGoodsStock,
                    "" + goods.getId(),
                    goods.getGoodsStock()
            );
            // 初始化为所有商品均可以秒杀
            killEndFlag.put(goods.getId(), false);
        }
    }

    @PostMapping(value = "/try")
    public void haveATry() {
        List<Integer> numList = new ArrayList<>();
        for(int i = 0; i < 100000; ++i) {
            numList.add(i);
        }
        long start = System.currentTimeMillis();
        numList.parallelStream().forEach(num -> sender.sendKillMessage(new OrderMessage(num, 0)));
        long end = System.currentTimeMillis();
        System.out.println("Oh My God: " + (end - start));
    }

    /**
     * 秒杀下单
     */
    @PostMapping(value = "/do_kill")
    public BaseResponse<Object> kill(@RequestParam("userId") long userId, @RequestParam("goodsId") long goodsId) {
        // 根据内存标记判断当前商品是否可以被秒杀
        if (killEndFlag.get(goodsId)) {
            return BaseResponse.error(ResultCode.KILL_END);
        }

        // 预减库存
        // redis 中当前商品的库存数量减一然后返回
        long stock = redisService.decr(GoodsKey.getGoodsStock, "" + goodsId);

        // 接下来的用户无法买 (但本用户可以购买), 所以要设置内存标记为结束秒杀
        if (stock == 0) {
            killEndFlag.put(goodsId, true);
        }

        // 接下来的用户无法买与本用户都不可以购买)
        else if (stock < 0) {
            killEndFlag.put(goodsId, true); // 可以不设置内存标记为结束秒杀, 因为 stock == 0 的用户已经设置过
            return BaseResponse.error(ResultCode.KILL_END);
        }

        // 判断用户是否进行了重复的秒杀，即已经有成功的秒杀记录了
        Order order = orderService.getOrderByUserIdAndGoodsId(userId, goodsId);
        if (order != null) {
            return BaseResponse.error(ResultCode.REPEAT_KILL);
        }

        // 入队
        sender.sendKillMessage(
                new OrderMessage(userId, goodsId)
        );

        return BaseResponse.success();
    }

    /**
     * 查询秒杀结果
     */
    @GetMapping(value = "/result")
    public Order result(@RequestParam("userId") long userId, @RequestParam("goodsId") long goodsId) {
        return killService.getOrderResult(userId, goodsId);
    }

    /**
     * 重置数据库和 redis
     */
    @PostMapping("/reset")
    public boolean reset() {
        try {
            int stock = 100000;
            List<Goods> goodsList = goodsService.getAllGoods();
            for (Goods goods : goodsList) {
                redisService.set(GoodsKey.getGoodsStock, "" + goods.getId(), stock);
                killEndFlag.put(goods.getId(), false);
                goods.setGoodsStock(stock);
            }
            redisService.delete(GoodsKey.getGoodsList);
            redisService.delete(OrderKey.getOrderByUidGid);
            redisService.delete(SecondKillKey.isGoodsOver);
            killService.deleteAllOrders();
            goodsService.updateGoods(goodsList);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    @Scheduled(fixedRate = 1000)
    public void schedule() {
        orderService.batchInsert();
    }
}
